CriminalSoulsApi = Class.create({
  initialize: function (clientId, clientSecret, redirectUrl, oAuthToken) {
	this._clientId = clientId;
	this._clientSecret = clientSecret;
	this._redirectUrl = redirectUrl;
	this._oAuthToken = oAuthToken;
  },
  isAuthorized: function () {
	return this._oAuthToken != '';
  },
  getOAuthToken: function () {
    return this._oAuthToken;
  },
  authorize: function () {
	var expires = new Date();
	expires.setHours(expires.getHours() + 1);
    document.cookie = 'csOAuthReturnUrl=' + window.location.href + '; expires=' + expires.toGMTString() + '; path=/';
    window.location.href = '/oauth/authorize' +
      '?response_type=code' +
      '&client_id=' + this._clientId + 
      '&redirect_uri=' + this._redirectUrl + 
      '&scope=basicInfo+email+inventory+stashedItems+friends';
  },
  apiRequest: function (path, params, onSuccess, onFailure) {
    var url = "/v1" + path;
    
    if (params) {
	  url += '?';
	  var first = true;
	  $H(params).each(function(pair){
	    if (!first)
	      url += '&';
	    url += encodeURIComponent(pair.key) + '=' + encodeURIComponent(pair.value);
	  	first = false;
	  });
    }
    
    new Ajax.Request(url, {
      requestHeaders: {
        Authorization: 'OOAuth ' + this._oAuthToken
      }, 	
      onSuccess: function(response) {
        if (Object.isFunction(onSuccess)) {
          onSuccess(response);
        } 
      },
      onFailure: function(response) {
        if (Object.isFunction(onFailure)) {
          onFailure(response);
        } else {
          alert('Error occured while executing api query ' + url + ':' + response.responseText);
        }
      }
    });
  }
});